<?php

$loader->requireOnce('controllers/C_Patient.class.php');
$loader->requireOnce('includes/EmerProcessor.class.php');
$loader->requireOnce('includes/CommonConstant.class.php');

/**
 * Controller of all actions related to reception tasks of Emergency department

 * @package modules.dept_emer.controllers
 * @author LHV
 * @version $Id$
 * @copyright 2009 LHV Company
 *
 */
class C_EmerReception extends Controller {

	private $logger;

    function C_EmerReception($template_mod = "general") {
        parent::Controller();
    	if (Celini::getCurrentController() == 'EmerReception') {
			$menu =& Menu::getInstance();
			$menu->currentSection = 'patient';
		}
        $this->template_mod = $template_mod;
        $this->view->path = 'emer_reception';

        $this->logger = LoggerManager::getLogger('emer_dept.controllers.C_EmerReception');
    }

    public function actionLoadEmerInfo() {
    	if (isset($_GET['patientId'])) {
            $patientId    =   $_GET['patientId'];
    	}
    	// EmerReception object
    	$objReception  =   Celini::newORDO('EmerReception')->getLatestObjectByPatientId($patientId);
		$this->_assignCommonVariables($objReception);
		$this->_assignEmergencyVariables($objReception);
		$this->_assignAllergyInfo($patientId);

        return $this->view->render("emergency_info.html");
    }

    public function actionSaveEmerInfoAjax() {
    	$recepId	=   $_POST['receptionIdHdn'];
    	$reception	=   Celini::newORDO('EmerReception', $recepId);
    	// Get patient & peson objetcs by provided receptionId if any
    	$patientId	=   $reception->getPatientId();

    	$patientId	= $this->_savePersonCommonInfo($patientId);
    	$this->_saveEmergencyInfo($recepId, $patientId);
    	// Fix 926: [Emer]  Check-in dept: update patient's name in common info bar
    	$person		=   Celini::newORDO('Person', $patientId);
    	// Save allergy info
    	$ticketId	=	Celini::newORDO('Ticket')->getLatestTicketIdByDepartment($patientId, $this->_me->get_department_id());
    	$this->_saveAllergyInfo($ticketId);
    	
    	return json_encode(array('patientName' => $person->getName()));
    }

    /**
     * Load page to input reception info.
     *
     * @param mixed $receptionId id of a specific reception object
     */
    public function actionRegister($receptionId = ''){
    	if (isset($_GET['receptionId'])) {
            $receptionId    =   $_GET['receptionId'];
    	}
    	// EmerReception object
    	$objReception  =   Celini::newORDO('EmerReception', $receptionId);
		$this->_assignCommonVariables($objReception);
		$this->_assignEmergencyVariables($objReception);
		$this->_assignDemographicsVariables($objReception->getPatientId());

        $this->assign('formAction', '../EmerReception/saveRegistrationInfo');
        return $this->view->render("reception.html");
    }

    /**
     * Save emergency registration information
     *
     * @return unknown
     */
    public function actionSaveRegistrationInfo(){
    	$recepId   =   $_POST['receptionIdHdn'];
    	$reception =   Celini::newORDO('EmerReception', $recepId);
    	// Get patient & peson objetcs by provided receptionId if any
    	$patientId =   $reception->getPatientId();

    	$patientId = $this->_savePersonCommonInfo($patientId);
    	$this->_saveDemographicsInfo($patientId);
    	$recepId = $this->_saveEmergencyInfo($recepId, $patientId);

    	$reception->setup($recepId);
        if ($reception->getInjuryLevel() == EmerReception::ENUM_INJ_LEVEL_DEAD){
            Celini::redirect('EmerReception', 'reportDeadOutside', array('patientId' => $patientId));
        }
        else {
        	$objEmerProcessor	=   new EmerProcessor($this);
        	$ticketId			=	$objEmerProcessor->checkInPatient($patientId, $this->_me->get_department_id(), date('Y-m-d H:i:s'),
        	    CommonConstant::IN_PATIENT,
                EnumerationConstant::PATIENT_SUB_STATUS_EMER_EMERGENCY);
            $this->_saveAllergyInfo($ticketId);
        
	        Celini::redirect('Queue', 'renderQueue');
        }
    }

    private function _assignCommonVariables($objReception) {
    	// Get patient & peson objetcs by provided receptionId
        $patientId =   $objReception->getPatientId();
        $objPerson    =   Celini::newORDO('Person', $patientId);
        $objPatient   =   Celini::newORDO('Patient', $patientId);
        $birthDays    =   L10nHelper::getDateParts($objPerson->getLocalizedDate('date_of_birth'));

        $this->assign_by_ref('reception', $objReception);
        $this->assign_by_ref('person', $objPerson);
        $this->assign_by_ref('patient', $objPatient);
        $this->assign('birthDays', $birthDays);
    }

    private function _assignEmergencyVariables($objReception) {
    	$receptionId = $objReception->get_id();
    	if ($objReception->get_id() > 0){
            $checkInDates  =   L10nHelper::getDateParts($objReception->getCheckInDate());
            $checkInTime   =   $objReception->getCheckInTime();
    	}
    	else {
    	   $curDate        =   L10nHelper::renderDateTime(date('Y-m-d'));
    	   $checkInDates   =   L10nHelper::getDateParts($curDate);
    	   $checkInTime    =   date('H:i');
    	}
        // Date order
        $orders =   L10nHelper::getYMDorder();

    	$this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);
        $this->assign('checkInDate', $checkInDates);
        $this->assign('checkInTime', $checkInTime);
        $this->assign('receptionId', $receptionId);


        // Enumerations
        //$objEm =   & Celini::enumManagerInstance();
        //$injuryLevelList    =  $objEm->enumArray(EnumerationConstant::EMER_REC_INJ_LEVEL);
        //$transportList      =  $objEm->enumArray(EnumerationConstant::EMER_REC_TRANSPORT);
        //localize enum by Viet Hoang
        $injuryLevelList    =  Utils::getEnumArrayKey(EnumerationConstant::EMER_REC_INJ_LEVEL);
        $transportList      =  Utils::getEnumArrayKey(EnumerationConstant::EMER_REC_TRANSPORT);

        $this->assign('injuryLevelList', $injuryLevelList);
        $this->assign('transportList', $transportList);
    }

    private function _assignDemographicsVariables($patientId) {
    	$objPerson = Celini::newORDO('Person', $patientId);

    	// Address of the person
        $addId     =   $objPerson->getAddressId();
        $address   =   Celini::newORDO('Address', $addId);
        // Insurance of the patient
        $objInsurance   =   Insurance::fromPatientId($patientId);
        if ($objInsurance->get_id() > 0){
            $expiredDates   =   L10nHelper::getDateParts($objInsurance->getExpiredDate());
        }
        else {
        	$expiredDates  =   array('', '', '');
        }

        $this->assign_by_ref('insurance', $objInsurance);
        $this->assign('terminationDates', $expiredDates);

    	$provinceList   =   ORDataObject::factory('Province')->getProvinceList();
        $districtList   =   ORDataObject::factory('District')->getDistrictList(C_Patient::DEFAULT_PROVINCE);
        $wardList       =   ORDataObject::factory('Ward')->getWardList(C_Patient::DEFAULT_DISTRICT);
        $countryList    =   ORDataObject::factory('Country')->getCountryListForSelect();
        $trlPatient     =   new C_Patient();
        $careerList     =   $trlPatient->getCareerList();
        $wokingDistrictList =  ORDataObject::factory('District')->getDistrictList($objPerson->getWorkingProvinceId());

        $this->assign('provinceList', $provinceList);
        $this->assign('districtList', $districtList);
        $this->assign('wardList', $wardList);
        $this->assign('countryList', $countryList);
        $this->assign('careerList', $careerList);
        $this->assign('wokingDistrictList', $wokingDistrictList);

        // Default values
        if ($objPerson->get_id() > 0) {
        	$nationality   =   $objPerson->getNationality();
        	$province      =   $objPerson->getProvinceId();
        	$district      =   $objPerson->getDistrictId();
        }
        else {
        	$nationality   =   C_Patient::DEFAULT_COUNTRY;
        	$province      =   C_Patient::DEFAULT_PROVINCE;
        	$district      =   C_Patient::DEFAULT_DISTRICT;
        }
        $this->assign('nationality', $nationality);
        $this->assign('province', $province);
        $this->assign('district', $district);
    }
    
    private function _assignAllergyInfo($patientId){
    	$ticketId			=	Celini::newORDO('Ticket')->getLatestTicketIdByDepartment($patientId, $this->_me->get_department_id());
    	$generalDiagnosis	=	Celini::newORDO('GeneralDiagnosis')->getGeneralDiagnosis($ticketId);
    	if($generalDiagnosis != null){
    		$this->assign('allergy', $generalDiagnosis['allergy']);
    		$this->assign('generalAllergy', $generalDiagnosis['general_allergy_detail']);
    		$this->assign('drugAllergy', $generalDiagnosis['drug_allergy_detail']);
    	}
    }

    private function _savePersonCommonInfo($patientId) {
    	$_POST['person']['name']       =   Utils::sanitizeAndCaseTitle($_POST['person']['name']);
        if(empty($_POST['person']['name'])){
            $_POST['person']['name']   =   "N/A";
        }
        $person    =   Celini::newORDO('Person', $patientId);
        $person->populateArray($_POST['person']);
        $person->persist();
        return $person->get_id();
    }

	private function _saveDemographicsInfo($patientId) {
		$person    =   Celini::newORDO('Person', $patientId);
		$patient   =   Celini::newORDO('Patient', $patientId);
    	// Address of the person
    	$addId     =   $person->getAddressId();
    	$address   =   Celini::newORDO('Address', $addId);
        // Insurance of the patient
        $insurance  =   Insurance::fromPatientId($patientId);

    	$_POST['address']['street']             =   Utils::sanitizeAndCaseTitle($_POST['address']['street']);
        $_POST['patient']['relative_name']      =   Utils::sanitizeAndCaseTitle($_POST['patient']['relative_name']);
        $_POST['patient']['relative_address']   =   Utils::sanitizeAndCaseTitle($_POST['patient']['relative_address']);
        $_POST['address']['ward_name']          =   Utils::sanitizeWard($_POST['address']['ward_name']);

        // Add address first to get address_id
        $address->populateArray($_POST['address']);
        $address->persist();

        // person
        $_POST['person']['address_id'] = $address->getId();

        $dates['year']  =   (int)Utils::sanitizeText($_POST['person']['DOB_yyyy']);
        $dates['month'] =   (int)Utils::sanitizeText($_POST['person']['DOB_mm']);
        $dates['day']   =   (int)Utils::sanitizeText($_POST['person']['DOB_dd']);
        $_POST['person']['date_of_birth']   =   L10nHelper::getISODate($dates);
        $person->populateArray($_POST['person']);
        $person->persist();

	  // patient
        $patientId = $person->getId();
        $_POST['patient']['person_id'] =  $patientId;
        $patientCode    =   $patient->getPatientCode();
        if (empty($patientCode)){
            $_POST['patient']['patient_code'] = $patient->genCode();
        }
        $patient->populateArray($_POST['patient']);
        $patient->persist();

        // Medical insurance registered hospital
        if(isset($_POST['registeredHospitalTxt']) && !empty($_POST['registeredHospitalTxt'])){
            $hospitalName   =   Utils::sanitizeAndCaseTitle($_POST['registeredHospitalTxt']);
            if(!empty($hospitalName)){
                $hospital   =   &ORDataObject::factory('Hospital');
                $hospitalId =   $hospital->getIdFromName($hospitalName);
                if($hospitalId > 0){
                    $_POST['insurance']['registered_hospital_id']   =   $hospitalId;
                }
                else{
                    $field      =   L10nHelper::changeField(L10nHelper::getLocale(),"name");
					$data = array(
						$field = $hospitalName
					);
                    $hospital-> populateArray($data);
                    $hospital->persist();
                    $_POST['insurance']['registered_hospital_id']   =   $hospital->getId();
                }
            }
        }

        // insurance last
        if (isset($_POST['insurance']) && ($_POST['insurance']['insurance_code'] != '')) {
            $expiredDate['year']    =   (int)Utils::sanitizeText($_POST['insurance']['expired_yyyy']);
            $expiredDate['month']   =   (int)Utils::sanitizeText($_POST['insurance']['expired_mm']);
            $expiredDate['day']     =   (int)Utils::sanitizeText($_POST['insurance']['expired_dd']);
            $_POST['insurance']['date_expired'] =   L10nHelper::getISODate($expiredDate);
            $_POST['insurance']['patient_id'] = $patientId;
            $insurance->populateArray($_POST['insurance']);
            $insurance->persist();
        }
        elseif ($insurance->get_id() > 0) {
        	$insurance->setData($patientId, '', '', '', '', '');
        	$insurance->persist();
        }
    }

	private function _saveEmergencyInfo($recepId, $patientId) {

		$reception =   Celini::newORDO('EmerReception', $recepId);

    	$aiderName      =   Utils::sanitizeAndCaseTitle($_POST['aiderNameTxt']);
        $aiderPhone     =   Utils::sanitizeText($_POST['aiderPhoneTxt']);
        $aiderAddress   =   Utils::sanitizeText($_POST['aiderAddressTxt']);
        $checkInTime['year']   =   Utils::sanitizeText($_POST['checkIn_yyyy']);
        $checkInTime['month']  =   Utils::sanitizeText($_POST['checkIn_mm']);
        $checkInTime['day']    =   Utils::sanitizeText($_POST['checkIn_dd']);
        $timeCheckIn    =   L10nHelper::getISODate($checkInTime) . " " . Utils::sanitizeText($_POST['checkInTimeTxt']);
        $reason         =   Utils::sanitizeText($_POST['reasonTxt']);
        $injuryDes      =   Utils::sanitizeText($_POST['injuryDescriptionTxt'], false);
        $injuryLevel    =   null;
        if(isset($_POST['injuryLevelRdb'])){
            $injuryLevel    =   $_POST['injuryLevelRdb'];
        }
        $injuryLevel   =   null;
        if(isset($_POST['injuryLevelRdb'])){
            $injuryLevel    =   $_POST['injuryLevelRdb'];
        }
        $transport  =   null;
        if(isset($_POST['transportRdb'])){
            $transport    =   $_POST['transportRdb'];
        }
        $fromPlace  =   Utils::sanitizeText($_POST['orignalPlaceTxt']);
        $preDiag    =   Utils::sanitizeText($_POST['preDiagnosisTxt'], false);
        
        // Set reception data
        $reception->setData($patientId, $aiderName, $aiderPhone, $aiderAddress,
            $timeCheckIn, $reason, $injuryDes, $injuryLevel, $fromPlace,
            $transport, $preDiag, $this->_me->get_person_id());
        // Persist
        $reception->persist();
        return $reception->get_id();
    }
    
    private function _saveAllergyInfo($ticketId){
        $allergy	=	$_POST['allgergyChk'];
        if($allergy == 'on'){
        	$allergy = true;
        }
        else{
        	$allergy = false;
        }
        $generalAllergy	=	null;
        $drugAllergy	=	null;
        if($allergy == true && isset($_POST['generalAllergyTxt'])){
        	$generalAllergy = Utils::sanitizeText($_POST['generalAllergyTxt']);
        }
		if($allergy == true && isset($_POST['drugAllergyTxt'])){
        	$drugAllergy = Utils::sanitizeText($_POST['drugAllergyTxt']);
        }
	    
		$emerProcessor	=	new EmerProcessor();
		$emerProcessor->saveAllergyInfo($ticketId, $allergy, $generalAllergy, $drugAllergy);
    }

    /**
     * Show page to input information on a patient died before checked-in to hospital
     *
     * @param int $patientId id of reported patient
     * @return unknown
     */
    public function actionReportDeadOutside($patientId = 0){
        // Person object
        $objPatient     =   Celini::newORDO('Person', $patientId);
        // Localized birthday
        $birthDay       =   $objPatient->getLocalizedDate('date_of_birth');
        // EmerReception object
        $objReception   =   ORDataObject::factory('EmerReception')->getLatestObjectByPatientId($patientId);
    	// Career list
    	$trlPatient =   new C_Patient();
        $careerList =   $trlPatient->getCareerList();
        // Doctor list
        $departmentId  =   $this->_me->get_department_id(); //TODO: Consider get departmentId by other source
        $doctorList =   ORDataObject::factory('Employee')->getEmployeeOfDepartment($departmentId, EmployeeType::DOCTOR_ID, true);
        $orders     =   L10nHelper::getYMDorder();
        $provinceList =     ORDataObject::factory('Province')->getProvinceList();
        $districtList =     ORDataObject::factory('District')->getDistrictList($objPatient->getProvinceId());
        
        $objDeathInfo   =   ORDataObject::factory('DeathOutsideInfo')->getLatestObjectByPatientId($patientId);
        
         // Check-in datetime

        if($objDeathInfo > 0) {
            $checkInDate =   L10nHelper::getDateParts($objDeathInfo->getCheckInDate());
            $checkInTime =   $objDeathInfo->getCheckInTime();
        }
        else {
            $checkInDate =   L10nHelper::getDateParts($objReception->getCheckInDate());
            $checkInTime =   $objReception->getCheckInTime();
        }
        $this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);
        $this->assign('careerList', $careerList);
        $this->assign('patientId', $patientId);
        $this->assign('doctorList', $doctorList);
        $this->assign('birthDays', L10nHelper::getDateParts($birthDay));
        $this->assign('checkInDate', $checkInDate);
        $this->assign('checkInTime', $checkInTime);
        $this->assign('provinceList', $provinceList);
        $this->assign('districtList', $districtList);
        $this->assign_by_ref('patient', $objPatient);
        $this->assign_by_ref('reception', $objReception);
        $this->assign_by_ref('deathInfo', $objDeathInfo);

        return $this->view->render('report_dead_outside.html');
    }

    /**
     * Save information of an report on a patient died before checked-in to hospital
     *
     * @param int $deathInfoId provided id of an DeathInfo object
     * @return id of DeathInfo object created
     */
    public function actionSaveReportDeadOutsideInfo($patientId = 0){
        if (isset($_POST['patientIdHdn'])){
            $patientId =   $_POST['patientIdHdn'];
        }
    	$objDeathInfo  =   ORDataObject::factory('DeathOutsideInfo')->getLatestObjectByPatientId($patientId);

        $objPerson  =   Celini::newORDO('Person', $patientId);
        $addId      =   $objPerson->getAddressId();
        $objAddress =   Celini::newORDO('Address', $addId);

        // Address object
        $address    =   Utils::sanitizeAndCaseTitle($_POST['addressTxt']);
        $provinceId =   $_POST['provinceLbx'];
        $districtId =   $_POST['districtLbx'];
        $wardName   =   $_POST['wardNameTxt'];
        $objAddress->populateArray(array(
            'street'        =>  $address,
            'province_id'   =>  $provinceId,
            'district_id'   =>  $districtId,
            'ward_name'     =>  $wardName));
        $objAddress->persist();

        // Person object
        $dates['year']  =   (int)Utils::sanitizeText($_POST['DOB_yyyy']);
        $dates['month'] =   (int)Utils::sanitizeText($_POST['DOB_mm']);
        $dates['day']   =   (int)Utils::sanitizeText($_POST['DOB_dd']);
        $name   =   Utils::sanitizeAndCaseTitle($_POST['patientNameTxt']);
        $career =   $_POST['careerLbx'];
        $objPerson->populateArray(array(
            'name'      =>  $name,
            'career_id' =>  $career,
            'date_of_birth' =>  L10nHelper::getISODate($dates)
        ));
        $objPerson->persist();

        // DeathInfo object
        $pulse          =   Utils::sanitizeText($_POST['pulseTxt']);
        $respiratory    =   Utils::sanitizeText($_POST['respiratoryTxt']);
        $pupilDistance  =   Utils::sanitizeText($_POST['pupilDistanceTxt']);
        $reflection     =   Utils::sanitizeText($_POST['lightReflectionTxt']);
        $other          =   Utils::sanitizeText($_POST['otherInjuryDesTxt']);
        $cause          =   Utils::sanitizeText($_POST['deadCauseTxt']);
        $conclusion     =   Utils::sanitizeText($_POST['conclusionTxt']);
        $checkInTime['year']   =   Utils::sanitizeText($_POST['checkIn_yyyy']);
        $checkInTime['month']  =   Utils::sanitizeText($_POST['checkIn_mm']);
        $checkInTime['day']    =   Utils::sanitizeText($_POST['checkIn_dd']);
        $timeCheckIn    =   L10nHelper::getISODate($checkInTime) . " " . Utils::sanitizeText($_POST['checkInTimeTxt']);
        $aiderName      =   Utils::sanitizeAndCaseTitle($_POST['aiderNameTxt']);
        $aiderPhone     =   Utils::sanitizeText($_POST['aiderPhoneTxt']);
        $aiderAddress   =   Utils::sanitizeText($_POST['aiderAddressTxt']);
        $relative       =   Utils::sanitizeText($_POST['relativeInfoTxt']);
        $emerAction     =   Utils::sanitizeText($_POST['emerActionTxt'], false);
        $property       =   Utils::sanitizeText($_POST['propertyTxt'], false);
        $doctorId       =   $_POST['doctorLbx'];
        $nurses			=	Utils::sanitizeText($_POST['partiNurseTxt']);
        $interns		=	Utils::sanitizeText($_POST['partiInternTxt']);
        
        $deathInfo		=	array(
        	 'patient_id'				=>	$patientId,
			 'doctor_id' 				=>	$doctorId,
			 'check_in_time' 			=>	$timeCheckIn,
			 'aid_giver_name' 			=> 	$aiderName,
			 'aid_giver_address' 		=> 	$aiderAddress,
			 'aid_giver_phone' 			=> 	$aiderPhone,
			 'relative_contacts' 		=> 	$relative,
			 'patient_possesion' 		=> 	$property,
			 'description_pulse' 		=> 	$pulse,
			 'description_respiratory' 	=> 	$respiratory,
			 'description_pupillary_distance'	=> $pupilDistance,
			 'description_light_reflex'	=> 	$reflection,
			 'description_other' 		=> 	$other,
			 'medication_process' 		=> 	$emerAction,
			 'death_caution' 			=> 	$cause,
			 'conclusion' 				=> 	$conclusion,
			 'participant_nurse' 		=> 	$nurses,
			 'participant_others' 		=> 	$interns
        );
        
        $objDeathInfo->populateArray($deathInfo);
        $objDeathInfo->persist();

        

         // FIXME ppdong 2009_07_22: finish return
         $reponse['deathOutsideInfoId']    =   $objDeathInfo->get_id();
         return json_encode($reponse);
    }
}
?>